package com.wzy.netty.core.simple;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * 描述  :  入门netty 案例
 * 创建人:    Wzy
 * 创建时间: 2020-06-11  11:22
 */
public class NettyServer {
    public static void main(String[] args) {

        /* loopgroup 中默认创建 cpu核心数*2的线程数量的loopgroup*/
        /**
         * bossLoopGroup 一般设置为1个循环eventLoop
         */
        NioEventLoopGroup bossLoopGroup = new NioEventLoopGroup(1);
        NioEventLoopGroup workerLoopGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossLoopGroup, workerLoopGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        //initChannel将在Channelpipeline中安装一组自定义的ChannelHandler，pipeline 中 包含了 handler链
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            //如果想实现自定义的推送业务逻辑，可以使用一个集合管理 socketChannel，在推送消息的时候，可以将业务加入到各个channel对应的NioEventLoop 的 taskQueue 或者 scheduleQueue

                            System.out.println("客户端的socketchannel:" + socketChannel.hashCode());
                            //此处可以使用一个集合管理所有注册的channel,以便于后面推送消息 ,可以将业务加入到各个channel
                            //对应的NIOEventLoop的taskQueue;
                            socketChannel.pipeline().addLast(new NettyServerHandler());
                        }
                    });
            System.out.println("服务端初始化 基本完毕");
//            绑定一个端口并同步，生成一个channelFuture对象
            ChannelFuture channelFuture = serverBootstrap.bind(6666).sync();
            //对关闭通道进行监听
            channelFuture.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            bossLoopGroup.shutdownGracefully();
            workerLoopGroup.shutdownGracefully();
        }
    }
}
